import logging
import time
from datetime import datetime, timedelta
from flask import request, render_template, session, redirect, g, jsonify
from info import constants, db
from info.models import User, News, Category
from info.until.common import outside
from info.until.qiniu_third import storage
from info.until.response_code import RET
from . import admin_blu


@admin_blu.route('/login', methods=["get", "post"])
def admin_login():
    if request.method == "GET":
        id = session.get("id", None)
        is_admin = session.get("is_admin", False)
        if all([id, is_admin]):
            return redirect("/admin/index")
        return render_template("admin/login.html")
    else:
        admin_name = request.form.get("username")
        admin_password = request.form.get("password")

        if not all([admin_name, admin_password]):
            return render_template("admin/login.html", errmsg="参数不足")
        try:
            result = User.query.filter(User.mobile == admin_name).first()
        except Exception as e:
            logging.error(e)
            return render_template("admin/login.html", errmsg="查询错误")

        if not result:
            return render_template("admin/login.html", errmsg="该管理员不存在")

        if not result.check_password(admin_password):
            return render_template("admin/login.html", errmsg="密码错误")

        session["id"] = result.id
        session["nick_name"] = admin_name
        session["mobile"] = result.mobile
        session["is_admin"] = result.is_admin

        return redirect("/admin/index")


@admin_blu.route('/logout')
def admin_logout():
    """
    清除登入状态
    :return:
    """
    session.pop("id", None)
    session.pop("nick_name", None)
    session.pop("is_admin", None)
    session.pop("mobile", None)

    return redirect("/admin/index")


@admin_blu.route('/index')
@outside
def admin_index():
    use = g.use
    data = {
        "use": use.to_dict()
    }
    return render_template("admin/index.html", data=data)


@admin_blu.route('/user_count')
def user_count():
    """
    计算当前的时间（可以百度查询）
    :return:
    """

    user_total = 0
    user_mouth = 0
    user_day = 0
    # 总用户
    try:
        user_total = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        logging.error(e)
    # 月新增数
    t = time.localtime()  # 当前的时间
    # 将时间字符串转换成对象
    mon_time = datetime.strptime('%d-%02d-01' % (t.tm_year, t.tm_mon), "%Y-%m-%d")
    try:
        user_mouth = User.query.filter(User.create_time > mon_time, User.is_admin == False).count()
    except Exception as e:
        logging.error(e)

    # 日新增数

    day_time = datetime.strptime('%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday), "%Y-%m-%d")
    try:
        user_day = User.query.filter(User.create_time > day_time, User.is_admin == False).count()
    except Exception as e:
        logging.error(e)

    # 显示折线
    # 当天的活跃人数等于当天24：00的活跃人数减去00：00的活跃人数
    # 当天的00：00
    today_time = datetime.strptime('%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday), "%Y-%m-%d")
    count_li = []
    day = []
    for i in range(0, 31):
        # 每天的00：00
        today_begin_time = today_time - timedelta(days=i)
        # 每天的24：00
        today_last_time = today_time - timedelta(days=(i - 1))
        count = User.query.filter(User.is_admin == False, User.last_login <= today_last_time,
                                  User.last_login >= today_begin_time).count()
        count_li.append(count)
        # 将时间对象转换成时间字符串
        day.append(today_begin_time.strftime("%Y-%m-%d"))

    count_li.reverse()
    day.reverse()

    data = {
        "user_total": user_total,
        "user_mouth": user_mouth,
        "user_day": user_day,
        "count_li": count_li,
        "day": day
    }
    return render_template("admin/user_count.html", data=data)


@admin_blu.route('/user_list')
def user_list():
    page = request.args.get("page", 1)
    total_page = 1
    user_items = []
    try:
        page = int(page)
    except Exception as e:
        logging.error(e)
    try:
        paginate = User.query.filter(User.is_admin == False).paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT)
        user_items = paginate.items
        total_page = paginate.pages
        page = paginate.page
    except Exception as e:
        logging.error(e)

    user_items_li = []
    for user in user_items:
        user_items_li.append(user.to_dict())
    data = {
        "total_page": total_page,
        "current_page": page,
        "user_items_li": user_items_li
    }

    return render_template("admin/user_list.html", data=data)


@admin_blu.route('/news_check')
def news_check():
    page = request.args.get("page", 1)
    keywords = request.args.get("keywords", None)
    try:
        page = int(page)
    except Exception as e:
        logging.error(e)
        page = 1
    news_items = []
    total_page = 1
    filters = [News.status == 1]
    if keywords:
        filters.append(News.title.contains(keywords))
    try:
        news = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,
                                                                                      constants.ADMIN_NEWS_PAGE_MAX_COUNT)
        total_page = news.pages
        page = news.page
        news_items = news.items
    except Exception as e:
        logging.error(e)
    news_li = []
    for new in news_items:
        news_li.append(new.to_review_dict())

    data = {
        "news_li": news_li,
        "total_page": total_page,
        "current_page": page
    }
    return render_template("admin/news_review.html", data=data)


@admin_blu.route('/news_check_details/<int:news_id>')
def news_check_details(news_id):
    try:
        news_details = News.query.get(news_id)
    except Exception as e:
        logging.error(e)
        return render_template("admin/news_review_detail.html", errmsg="查询错误")
    if not news_details:
        return render_template("admin/news_review_detail.html", errmsg="未查到此新闻")
    data = {
        "news_details": news_details.to_dict()
    }
    return render_template("admin/news_review_detail.html", data=data)


@admin_blu.route('/news_review', methods=["post"])
def news_review():
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    reason = ""
    if action == "reject":
        reason = request.json.get("reason")
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        news_id = int(news_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if action not in ["reject", "accept"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        new = News.query.get(news_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据查询失败")
    if not new:
        return jsonify(errno=RET.NODATA, errmsg="未查到该新闻")
    if action == "accept":
        new.status = 0
    else:
        new.status = -1
        new.reason = reason

    return jsonify(errno=RET.OK, errmsg="ok")


@admin_blu.route('/news_edit')
def news_edit():
    page = request.args.get("page", 1)
    keywords = request.args.get("keywords", None)

    try:
        page = int(page)
    except Exception as e:
        logging.error(e)
        page = 1
    filters = [News.status == 0]
    if keywords:
        filters.append(News.title.contains(keywords))
    total_page = 1
    items_li = []
    try:
        news = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,
                                                                                      constants.ADMIN_NEWS_PAGE_MAX_COUNT)
        page = news.page
        total_page = news.pages
        items_li = news.items
    except Exception as e:
        logging.error(e)

    news_items = []
    for items in items_li:
        news_items.append(items.to_basic_dict())

    data = {
        "page": page,
        "total_page": total_page,
        "news_items": news_items
    }
    return render_template("admin/news_edit.html", data=data)


@admin_blu.route('/news_edit_details/<int:news_id>')
def news_edit_details(news_id):
    news = None
    try:
        news = News.query.filter(News.id == news_id).first()
    except Exception as e:
        logging.error(e)
    if not news:
        return render_template("admin/news_edit_detail.html", errmsg="未查出该新闻")

    try:
        category = Category.query.all()
    except Exception as e:
        logging.error(e)
        return render_template("admin/news_edit_detail.html", errmsg="数据库查询错误")

    category_li = []
    for categories in category:
        cate = categories.to_dict()
        cate["is_selected"] = False
        if news.category_id == cate["id"]:
            cate["is_selected"] = True
        category_li.append(cate)

    category_li.pop(0)

    data = {
        "news": news.to_dict() if news else None,
        "category_li": category_li
    }
    return render_template("admin/news_edit_detail.html", data=data)


@admin_blu.route('/news_edit_detail', methods=["post"])
def news_edit_detail():
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    content = request.form.get("content")
    news_id = request.form.get("news_id")
    index_image = request.files.get("index_image", None)

    if not all(["title", "category_id", "digest", "content", "news_id"]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        news_id = int(news_id)
        category_id = int(category_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据库查询错误")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到此新闻")

    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.content = content

    if index_image:
        index_image = index_image.read()
        ret_key = storage(index_image)
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + "/" + ret_key

    return jsonify(errno=RET.OK, errmsg="ok")


@admin_blu.route('/news_category',methods=["get","post"])
def news_category():
    if request.method=="GET":
        category=[]
        try:
            category = Category.query.all()
        except Exception as e:
            logging.error(e)

        category_li=[]
        for categories in category:
            category_li.append(categories.to_dict())
        category_li.pop(0)

        data={
            "category_li":category_li
        }

        return render_template("admin/news_type.html", data=data)

    else:
        edit= request.json.get("name")
        category_id= request.json.get("id")

        if not edit:
            return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
        if category_id:
            # 修改新闻的分类
            try:
                cate= Category.query.filter(Category.id==category_id).first()
            except Exception as e:
                logging.error(e)
                return jsonify(errno=RET.DATAERR,errmsg="数据库查询错误")
            if not cate:
                return jsonify(errno=RET.NODATA,errmsg="未查到该新闻分类")
            cate.name= edit
        else:
            # 没有id，就是增加一个分类
            cates = Category()
            cates.name = edit
            try:
                db.session.add(cates)
                db.session.commit()
            except Exception as e:
                logging.error(e)
                db.session.rollback()
        return jsonify(errno=RET.OK,errmsg="ok")
